using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Volo.Abp;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Guids;

namespace UserManagementService.Organizations;

/// <summary>
/// 组织实体
/// </summary>
public class Organization : FullAuditedAggregateRoot<Guid>, IMultiTenant
{
    /// <summary>
    /// 租户ID
    /// </summary>
    public Guid? TenantId { get; set; }

    /// <summary>
    /// 组织编码
    /// </summary>
    [Required]
    [StringLength(50)]
    public string Code { get; set; } = string.Empty;

    /// <summary>
    /// 组织名称
    /// </summary>
    [Required]
    [StringLength(200)]
    public string Name { get; set; } = string.Empty;

    /// <summary>
    /// 组织类型
    /// </summary>
    public OrganizationType Type { get; set; }

    /// <summary>
    /// 父组织ID
    /// </summary>
    public Guid? ParentId { get; set; }

    /// <summary>
    /// 组织层级
    /// </summary>
    public int Level { get; set; }

    /// <summary>
    /// 排序号
    /// </summary>
    public int Sort { get; set; }

    /// <summary>
    /// 组织描述
    /// </summary>
    [StringLength(500)]
    public string? Description { get; set; }

    /// <summary>
    /// 联系人
    /// </summary>
    [StringLength(100)]
    public string? ContactPerson { get; set; }

    /// <summary>
    /// 联系电话
    /// </summary>
    [StringLength(50)]
    public string? ContactPhone { get; set; }

    /// <summary>
    /// 联系邮箱
    /// </summary>
    [StringLength(200)]
    public string? ContactEmail { get; set; }

    /// <summary>
    /// 地址
    /// </summary>
    [StringLength(500)]
    public string? Address { get; set; }

    /// <summary>
    /// 是否启用
    /// </summary>
    public bool IsEnabled { get; set; } = true;

    /// <summary>
    /// 扩展属性（JSON格式）
    /// </summary>
    public string? Properties { get; set; }

    /// <summary>
    /// 子组织集合
    /// </summary>
    public virtual ICollection<Organization> Children { get; set; } = new List<Organization>();

    /// <summary>
    /// 组织成员集合
    /// </summary>
    public virtual ICollection<OrganizationMember> Members { get; set; } = new List<OrganizationMember>();

    protected Organization()
    {
    }

    public Organization(
        Guid id,
        Guid? tenantId,
        string code,
        string name,
        OrganizationType type,
        Guid? parentId = null,
        string? description = null)
        : base(id)
    {
        TenantId = tenantId;
        Code = Check.NotNullOrWhiteSpace(code, nameof(code), OrganizationConsts.MaxCodeLength);
        Name = Check.NotNullOrWhiteSpace(name, nameof(name), OrganizationConsts.MaxNameLength);
        Type = type;
        ParentId = parentId;
        Description = description;
        Level = CalculateLevel(parentId);
        Sort = 0;
    }

    /// <summary>
    /// 更新组织信息
    /// </summary>
    public Organization UpdateInfo(string name, string? description = null)
    {
        Name = Check.NotNullOrWhiteSpace(name, nameof(name), OrganizationConsts.MaxNameLength);
        Description = description;

        return this;
    }

    /// <summary>
    /// 设置父组织
    /// </summary>
    public Organization SetParent(Guid? parentId)
    {
        ParentId = parentId;
        Level = CalculateLevel(parentId);

        return this;
    }

    /// <summary>
    /// 启用组织
    /// </summary>
    public Organization Enable()
    {
        IsEnabled = true;
        return this;
    }

    /// <summary>
    /// 禁用组织
    /// </summary>
    public Organization Disable()
    {
        IsEnabled = false;
        return this;
    }

    /// <summary>
    /// 设置排序
    /// </summary>
    public Organization SetSort(int sort)
    {
        Sort = sort;
        return this;
    }

    /// <summary>
    /// 设置扩展属性
    /// </summary>
    public Organization SetProperties(string? properties)
    {
        Properties = properties;
        return this;
    }

    /// <summary>
    /// 计算组织层级
    /// </summary>
    private int CalculateLevel(Guid? parentId)
    {
        if (parentId == null)
            return 0;

        // 这里需要递归计算层级，实际实现中可能需要查询数据库
        return 1; // 简化实现
    }

    /// <summary>
    /// 添加成员
    /// </summary>
    public Organization AddMember(Guid userId, string? position = null, string? description = null)
    {
        var existingMember = Members.FirstOrDefault(m => m.UserId == userId);
        if (existingMember != null)
        {
            existingMember.UpdateInfo(position, description);
        }
        else
        {
            var member = new OrganizationMember(Guid.NewGuid(), Id, userId, position, description);
            Members.Add(member);
        }

        return this;
    }

    /// <summary>
    /// 移除成员
    /// </summary>
    public Organization RemoveMember(Guid userId)
    {
        var member = Members.FirstOrDefault(m => m.UserId == userId);
        if (member != null)
        {
            Members.Remove(member);
        }

        return this;
    }

    /// <summary>
    /// 检查是否为子组织
    /// </summary>
    public bool IsChildOf(Guid parentId)
    {
        return ParentId == parentId;
    }

    /// <summary>
    /// 获取组织路径
    /// </summary>
    public string GetPath()
    {
        // 这里需要递归构建组织路径
        return Code; // 简化实现
    }
}